package org.springblade.tms.global.utils;

import cn.hutool.core.text.StrBuilder;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.nacos.common.codec.Base64;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springblade.core.log.logger.BladeLogger;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.system.feign.IDictBizClient;
import org.springblade.tms.config.SpringContextHolder;
import org.springblade.tms.global.constant.DictCodeConstant;
import org.springblade.tms.global.exception.CommonException;
import org.springframework.http.MediaType;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static org.springblade.common.constant.TenantConstant.DEFAULT_TENANT_ID;
import static org.springblade.tms.global.constant.DictCodeConstant.*;

/**
 * @author: wzq
 * @className: HttpUtils
 * @createDate: 2022/3/8
 * @description: 封装HTTP请求
 */
@Slf4j
public final class HttpUtils {

	private HttpUtils() {
	}


	public static HttpResponse httpTaskResponse(
		String apiName, Method method,
		Map<String, String> header, Object paramUrl,
		Map<String, Object> paramMap,
		String body,
		String urlOriginal) {
		String url = urlOriginal;


		BladeLogger logger = SpringContextHolder.getBean(BladeLogger.class);
		StrBuilder tips = StrBuilder.create(
			apiName,
			method.name(),
			paramUrl == null ? null : JsonUtil.toJson(paramUrl),
			paramMap == null ? null : JsonUtil.toJson(paramMap),
			body,
			urlOriginal
		);
		log.info("====================请求接口名称====================" + apiName);
		log.info("====================请求地址====================" + url);
		log.info("====================请求体====================" + body);
		HttpResponse response;
		try {

			HttpRequest request = HttpUtil.createRequest(method, url);
			request.setMethod(method);
			Map<String, String> headerMap = new HashMap<>();

			if (Objects.isNull(header)) {

				if (Objects.nonNull(paramMap)) {
					//form表单
					headerMap.put("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
					request.form(paramMap);
				} else {
					headerMap.put("Content-Type", MediaType.APPLICATION_JSON_VALUE);
				}
				request.addHeaders(headerMap);
			} else {
				request.addHeaders(header);
			}

			if (Objects.nonNull(paramUrl)) {
				if (paramUrl instanceof String) {
					url = StrBuilder.create(url, Obj2UrlParamUtils.objToString(paramUrl)).toString();
				} else {
					url = StrBuilder.create(url, paramUrl.toString()).toString();
				}

			}


			if (Strings.isNotBlank(body)) {
				request.body(body);
			}
			log.info("====================请求头====================" + headerMap);
			log.info("====================请求头====================" + header);
			request.setUrl(url);
			response = request.executeAsync();

			log.info("请求返回信息" + response);
			tips.append(response.toString());
			logger.info(apiName, tips.toString());
		} catch (Exception e) {
			log.error("请求接口" + apiName + "失败", e);
			logger.error(apiName, "请求接口" + apiName + "失败");
			throw new CommonException(e);
		}
		return response;
	}

	/**
	 * @param method
	 * @param header
	 * @param body     json
	 * @param paramUrl 拼接url的熟悉
	 * @param paramMap form表单
	 * @return
	 */
	public static String httpTask(
		String apiName, Method method,
		Map<String, String> header, Object paramUrl,
		Map<String, Object> paramMap,
		String body,
		String urlOriginal) {
		return httpTaskResponse(apiName, method, header, paramUrl, paramMap, body, urlOriginal).body();
	}

	//sap鉴权封装
	public static String sapTask(String apiName, Method method,
								 Map<String, String> header, Object paramUrl,
								 Map<String, Object> paramMap,
								 String body, String urlCode) {
		IDictBizClient iDictBizClient = SpringContextHolder.getBean(IDictBizClient.class);
		String auth = iDictBizClient.getValue(THIRD_INTERFACE, DictCodeConstant.SAP_ACCOUNT_USER,DEFAULT_TENANT_ID).getData()
			+ ":" + iDictBizClient.getValue(THIRD_INTERFACE, DictCodeConstant.SAP_ACCOUNT_PASSWORD,DEFAULT_TENANT_ID).getData();
		byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("UTF-8")));
		String authHeader = "Basic " + new String(encodedAuth);
		header.put("Authorization", authHeader);
		String url = iDictBizClient.getValue(THIRD_INTERFACE, DictCodeConstant.SAP_URL,DEFAULT_TENANT_ID).getData();
		return httpTask(apiName, method, header, paramUrl, paramMap, body, url + urlCode);
	}

	//gps鉴权封装
	public static String gpsTask(String apiName, Method method,
								 Map<String, String> header, Object paramUrl,
								 Map<String, Object> paramMap,
								 String body, String urlCode) {
		IDictBizClient iDictBizClient = SpringContextHolder.getBean(IDictBizClient.class);
		header.put(STRATEGY_ID, iDictBizClient.getValue(THIRD_INTERFACE, DictCodeConstant.STRATEGY_ID,DEFAULT_TENANT_ID).getData());
		header.put(APIKEY, iDictBizClient.getValue(THIRD_INTERFACE, DictCodeConstant.APIKEY,DEFAULT_TENANT_ID).getData());
		header.put(AUTHORIZATION__TYPE, iDictBizClient.getValue(THIRD_INTERFACE, DictCodeConstant.AUTHORIZATION__TYPE,DEFAULT_TENANT_ID).getData());
		String url = iDictBizClient.getValue(THIRD_INTERFACE, DictCodeConstant.GPS_URL,DEFAULT_TENANT_ID).getData();
		return httpTask(apiName, method, header, paramUrl, paramMap, body, url + urlCode);
	}
}
